<template>
    <div ref="container" @dblclick="fullscreenSwich"
        style="width:100%;height:99%;background-color: #000000;margin:0 auto;position: relative;">
        <div class="buttons-box" id="buttonsBox">
            <div class="buttons-box-left">
                <i v-if="!playing" class="iconfont icon-play jessibuca-btn" @click="playBtnClick"></i>
                <i v-if="playing" class="iconfont icon-pause jessibuca-btn" @click="pause"></i>
                <i  class="iconfont icon-stop jessibuca-btn" @click="destroy"></i>
                <i v-if="isNotMute" class="iconfont icon-audio-high jessibuca-btn" @click="mute()"></i>
                <i v-if="!isNotMute" class="iconfont icon-audio-mute jessibuca-btn" @click="cancelMute()"></i>
            </div>
            <div class="buttons-box-right">
                <span class="jessibuca-btn">{{ kBps }} kb/s</span>
                <!--          <i class="iconfont icon-file-record1 jessibuca-btn"></i>-->
                <!--          <i class="iconfont icon-xiangqing2 jessibuca-btn" ></i>-->
                <i class="iconfont icon-camera1196054easyiconnet jessibuca-btn" @click="screenshot"></i>
                <i class="iconfont icon-shuaxin11 jessibuca-btn" @click="playBtnClick"></i>
                <i v-if="!fullscreen" class="iconfont icon-weibiaoti10 jessibuca-btn" @click="fullscreenSwich"></i>
                <i v-if="fullscreen" class="iconfont icon-weibiaoti11 jessibuca-btn" @click="fullscreenSwich"></i>
            </div>
        </div>
    </div>
</template>

<script setup>
import { onMounted, watch, onBeforeUnmount ,defineProps, toRefs , ref} from 'vue';
import { useRouter, useRoute } from 'vue-router';
let jessibucaPlayer = null;
const container = ref(null);
const playing = ref(false);
const isNotMute = ref(false);
const quieting = ref(false);
const fullscreen = ref(false);
const loaded = ref(false);
const speed = ref(0);
const performance = ref('');
const kBps = ref(0);
const btnDom = ref(null);
const videoInfo = ref(null);
const volume = ref(1);
const rotate = ref(0);
const vod = ref(true);
const _uid = ref('100')
const forceNoOffscreen = ref(false);
const route = useRoute();
const props = defineProps({
    videoUrl: String,
    error: String,
    hasAudio: Boolean,
    height: Number
})
const videoUrl = ref(props.videoUrl);
const error = ref(props.error);
const hasAudio = ref(props.hasAudio);
const height = ref(props.height);
// console.log(videoUrl.value, 'videoUrl   P');

onMounted(() => {
    window.onerror = (msg) => {
        // Handle global error here
    };
    const updatePlayerDomSize = () => {
        if (!container.value) return;
        let width = container.value.parentNode.clientWidth;
        let height = (9 / 16) * width;

        const clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight);
        if (height > clientHeight) {
            height = clientHeight;
            width = (16 / 9) * height;
        }
        // container.value.style.width = `${width}px`;
        // container.value.style.height = `${height}px`;
    };
    window.onresize = updatePlayerDomSize;
    updatePlayerDomSize();
    const video = videoUrl.value || decodeURIComponent(route.params.url);
    // const videoUrl = props.videoUrl ;
    // console.log(videoUrl, 'videoUrl');
    play(video);
});
// 处理视频URL变化
watch(() => props.videoUrl, (newVal, oldVal) => {
//   console.log(newVal, 'newUrl');
  play(newVal);
}, { immediate: false });
// 创建播放器实例
const create = () => {
    // 创建播放器实例的逻辑
    let options = {};
    // console.log("hasAudio  " + hasAudio)
    jessibucaPlayer = new window.Jessibuca(Object.assign(
        {
            container: container.value,
            autoWasm: true,
            background: "",
            controlAutoHide: false,
            debug: false,
            decoder: "decoder.js",
            forceNoOffscreen: true,
            hasAudio: typeof (hasAudio) == "undefined" ? true : hasAudio,
            hasVideo: true,
            heartTimeout: 5,
            heartTimeoutReplay: true,
            heartTimeoutReplayTimes: 3,
            hiddenAutoPause: false,
            hotKey: false,
            isFlv: false,
            isFullResize: false,
            isNotMute: isNotMute.value,
            isResize: false,
            keepScreenOn: false,
            loadingText: "请稍等, 视频加载中......",
            loadingTimeout: 10,
            loadingTimeoutReplay: true,
            loadingTimeoutReplayTimes: 3,
            openWebglAlignment: false,
            operateBtns: {
                fullscreen: false,
                screenshot: false,
                play: false,
                audio: false,
                record: false
            },
            recordType: "webm",
            rotate: 0,
            showBandwidth: false,
            supportDblclickFullscreen: false,
            timeout: 10,
            useMSE: location.hostname !== "localhost" && location.protocol !== "https:",
            useOffscreen: false,
            useWCS: location.hostname === "localhost" || location.protocol === "https",
            useWebFullScreen: false,
            videoBuffer: 0,
            wasmDecodeAudioSyncVideo: true,
            wasmDecodeErrorReplay: true,
            wcsUseVideoRender: true
        },
        options
    ));
    let jessibuca = jessibucaPlayer;
    jessibuca.on("load", function () {
        // console.log("on load init");
    });

    jessibuca.on("log", function (msg) {
        console.log("on log", msg);
    });
    jessibuca.on("record", function (msg) {
        console.log("on record:", msg);
    });
    jessibuca.on("pause", function () {
        playing.value = false;
    });
    jessibuca.on("play", function () {
        playing.value = true;
    });
    jessibuca.on("fullscreen", function (msg) {
        console.log("on fullscreen", msg);
        fullscreen.value = msg
    });

    jessibuca.on("mute", function (msg) {
        console.log("on mute", msg);
        isNotMute.value = !msg;
    });
    jessibuca.on("audioInfo", function (msg) {
        console.log("audioInfo", msg);
    });

    jessibuca.on("bps", function (bps) {
        // console.log('bps', bps);

    });
    let _ts = 0;
    jessibuca.on("timeUpdate", function (ts) {
        // console.log('timeUpdate,old,new,timestamp', _ts, ts, ts - _ts);
        _ts = ts;
    });

    jessibuca.on("videoInfo", function (info) {
        console.log("videoInfo", info);
    });

    jessibuca.on("error", function (error) {
        console.log("error", error);
    });

    jessibuca.on("timeout", function () {
        console.log("timeout");
    });

    jessibuca.on('start', function () {
        console.log('start');
    })

    jessibuca.on("performance", function (value) {
        let show = "卡顿";
        if (value === 2) {
            show = "非常流畅";
        } else if (value === 1) {
            show = "流畅";
        }
        performance.value = show;
    });
    jessibuca.on('buffer', function (buffer) {
        // console.log('buffer', buffer);
    })

    jessibuca.on('stats', function (stats) {
        // console.log('stats', stats);
    })

    jessibuca.on('kBps', function (kBp) {
        kBps.value = Math.round(kBp);
    });

    // 显示时间戳 PTS
    jessibuca.on('videoFrame', function () {

    })

    //
    jessibuca.on('metadata', function () {

    });
    jessibuca.on("playToRenderTimes", function (times) {
        // console.log("playToRenderTimes is", times)
    })
};

const playBtnClick = (event) => {
    play(videoUrl.value);
};

const pause = () => {
    if (jessibucaPlayer) {
        jessibucaPlayer.pause();
    }
    playing.value = false;
    // err.value = "";
    performance.value = "";
};

const screenshot = () => {
    if (jessibucaPlayer) {
        jessibucaPlayer.screenshot();
    }
};

const mute = () => {
    if (jessibucaPlayer) {
        jessibucaPlayer.mute();
    }
};

const cancelMute = () => {
    if (jessibucaPlayer) {
        jessibucaPlayer.cancelMute();
    }
};

const destroy = () => {
    // console.log('关闭');
    if (jessibucaPlayer) {
        jessibucaPlayer.destroy();
    }
    if (document.getElementById("buttonsBox") == null) {
        container.value.appendChild(btnDom.value);
    }
    jessibucaPlayer = null;
    playing.value = false;
    // err.value = "";
    performance.value = "";
};

const eventcallbacK = (type, message) => {
    // console.log("player 事件回调")
    // console.log(type)
    // console.log(message)
};

const fullscreenSwich = () => {
    let isFull = isFullscreen();
    jessibucaPlayer.setFullscreen(!isFull);
    fullscreen.value = !isFull;
};

const isFullscreen = () => {
    return document.fullscreenElement ||
        document.msFullscreenElement ||
        document.mozFullScreenElement ||
        document.webkitFullscreenElement || false;
};
const play = (url) => {
    // console.log(url , 'url');
    if (jessibucaPlayer) {
        destroy();
    }
    create();
    jessibucaPlayer.on("play", () => {
        playing.value = true;
        loaded.value = true;
        quieting.value = jessibuca.quieting;
    });
    if (jessibucaPlayer.hasLoaded()) {
        jessibucaPlayer.play(url);
    } else {
      
        jessibucaPlayer.on("load", () => {
            // console.log("load 播放");
            jessibucaPlayer.play(url);
        });
    }
};

onBeforeUnmount(() => {
    if (jessibucaPlayer) {
        jessibucaPlayer.destroy();
    }
    playing.value = false;
    loaded.value = false;
    performance.value = "";
});
</script>
<style>
.buttons-box {
    width: 100%;
    height: 28px;
    background-color: rgba(43, 51, 63, 0.7);
    position: absolute;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    left: 0;
    bottom: 0;
    user-select: none;
    z-index: 10;
}

.jessibuca-btn {
    width: 20px;
    color: rgb(255, 255, 255);
    line-height: 27px;
    margin: 0px 10px;
    padding: 0px 2px;
    cursor: pointer;
    text-align: center;
    font-size: 0.16rem !important;
}

.buttons-box-right {
    position: absolute;
    right: 0;
}
</style>
